#!/usr/bin/env python3

# Note : This file will be excuted in Docker Environment
# Do Not run this file in the Host Environment ! 

import os
import json
import re
import shutil
import platform

src_mount_point = "src_mnt"
tgt_mount_point = "tgt_mnt"

config_file = "config.json"

extra_package_list = ["dpkg"]

def get_package_name_list(rpmlistfile , remove_package_list) -> list:

    pattern = re.compile("^.+(?=-[\d|.|\w]+-)")

    with open(rpmlistfile,"r") as f:
        data = f.readlines()

    packageList = []

    for line in data:
        name = pattern.search(line).group()

        # Remove package form the list
        if any(filter(lambda x: x in name, remove_package_list)):
            continue

        packageList.append(name)
   
    return packageList

def check_env():

    if (platform.machine() != "aarch64"):
        print("Your machine architecture is {}, please use aarch64 architecture to run this script !".format(platform.machine()))
        exit(1)

    if not os.path.exists("/.dockerenv"):
        print("Error : This file must be excuted in docker environment !")
        exit(1)


if __name__ =="__main__":

    check_env()

    with open(config_file) as fd:
        config = json.load(fd)

    rpmlist_file = config["SourceFile"]
    image_name = config["ImageName"]
    extra_package_list = config["ExtraPackage"]
    remove_package_list = config["RemovePackage"]

    mirror_enable = config["MirrorRepoEnable"]

    if mirror_enable :
        mirror_source = config["MirrorRepoSource"]
        cmd = 'sed -i "s#repo.openeuler.org#{}#" /etc/yum.repos.d/openEuler.repo'
        os.system(cmd.format(mirror_source))
        
    if(os.path.exists(src_mount_point)):
        shutil.rmtree(src_mount_point);

    if(os.path.exists(tgt_mount_point)):
        shutil.rmtree(tgt_mount_point)

    os.mkdir(src_mount_point)
    os.mkdir(tgt_mount_point)


    packageList = get_package_name_list(rpmlist_file,remove_package_list)

    cmd = "dnf install -y --installroot " + os.path.join(os.getcwd() , src_mount_point)
    
    for item in packageList:
        cmd = cmd + " " + item

    for item in extra_package_list:
        cmd = cmd + " " + item

    # Install Edge Package to Rootfs
    os.system("dnf update --assumeno")

    os.system("dnf install -y util-linux")

    ret = os.system(cmd)
    if (ret != 0):
        exit(ret)

    # Create Ext4 Image File
    ret = os.system("./create_image.sh {} {} {}".format(image_name, src_mount_point,  tgt_mount_point))
    if (ret != 0):
        exit(ret)
